import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import javax.swing.JOptionPane;

public class Main {
	private DManagerFrame frame;
	public static final int ADDED_CMD = 1;

	// private final ConcurrentLinkedQueue<Download> queue = new
	// ConcurrentLinkedQueue<>();

	private ExecutorService threadPool = Executors.newCachedThreadPool();

	public static void main(String... args) {
		(new Main()).run();
	}

	private AtomicInteger fileid = new AtomicInteger(1);

	private void run() {
		final ActionListener incomeDLlistener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				switch (e.getID()) {
				case ADDED_CMD:
					final Download dl = (Download) e.getSource();
					final String urlstr = e.getActionCommand();
					threadPool.submit(new Runnable() {
						public void run() {
							URL url;
							try {
								url = new URL(urlstr);
								URLConnection connection = url.openConnection();
								int contentSize = connection.getContentLength();
								BufferedReader in;
								in = new BufferedReader(new InputStreamReader(
										connection.getInputStream()));
								String inputLine;
								PrintWriter pw = new PrintWriter(
										new FileWriter(
												"Downloads"
														+ System.getProperty("file.separator")
														+ "out"
														+ fileid.getAndIncrement()));
								int size = 0;
								// while ((inputLine = in.readLine() != null &&
								// inputLine.equals("\n"));
								while (!dl.isInterrupted()
										&& (inputLine = in.readLine()) != null) {
									size += inputLine.getBytes().length;
									int barprogress = (int) ((double) size
											/ (double) contentSize * 100);
									dl.pb.setValue(barprogress);
									pw.println(inputLine);
									synchronized (dl) {
										while (dl.isPaused()
												&& !dl.isInterrupted())
											try {
												dl.wait();
											} catch (InterruptedException e) {
												pw.close();
												in.close();
												dl.destroy();
												return;
											}
									}
								}

								pw.close();
								in.close();
								dl.pb.setValue(100);
							} catch (IOException e) {
								JOptionPane.showMessageDialog(frame, "URI not found!");
								dl.destroy();
							}
						}
					});

					break;
				default:
					return;
				}
			}
		};

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frame = new DManagerFrame(incomeDLlistener);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}
